<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0"/>
    <title>聊天室frm</title>
    <link rel="stylesheet" type="text/css" href="../css/aui.css" />
</head>
<style>
body {
	background-color: #EBEBEB;
}
.history-date { font-size: 12px;}
/*#message-content { overflow-y: auto;}*/

.aui-chat-receiver .aui-chat-receiver-cont {
	background: #ffffff;
}
.aui-chat-left-triangle {
	border-color: transparent #ffffff transparent transparent;
}

.aui-chat-sender .aui-chat-sender-cont {
	background: #15b5e9;
	color: #ffffff;
}

.aui-chat-right-triangle {
	border-color: transparent transparent transparent #15b5e9;
}
</style>
<body>
    <div class="aui-content aui-content-padded" id="message-content">
        <p class="aui-text-center history-date">7-16 20:00</p>
        <div class="aui-chat-sender">
            <div class="aui-chat-sender-avatar"><img src="../image/widget_dface.png"></div>
            <div class="aui-chat-sender-cont">
                <div class="aui-chat-right-triangle"></div>
                <span>Hello!!</span>
            </div>
        </div>
        <div class="aui-chat-receiver">
            <div class="aui-chat-receiver-avatar"><img src="../image/widget_dface.png"></div>
            <div class="aui-chat-receiver-cont">
                <div class="aui-chat-left-triangle"></div>
                <span>你好！</span>
            </div>
        </div>
        <div class="aui-chat-sender">
            <div class="aui-chat-sender-avatar"><img src="../image/widget_dface.png"></div>
            <div class="aui-chat-sender-cont">
                <div class="aui-chat-right-triangle"></div>
                <span>nice to meet you!</span>
            </div>
        </div>
        <div class="aui-chat-receiver">
            <div class="aui-chat-receiver-avatar"><img src="../image/widget_dface.png"></div>
            <div class="aui-chat-receiver-cont">
                <div class="aui-chat-left-triangle"></div>
                <span>很高兴见到你！</span>
            </div>
        </div>
        <div class="aui-chat-sender">
            <div class="aui-chat-sender-avatar"><img src="../image/widget_dface.png"></div>
            <div class="aui-chat-sender-cont">
                <div class="aui-chat-right-triangle"></div>
                <span>如果文字太长了会是什么效果，再多一点再多一点</span>
            </div>
        </div>
        <div class="aui-chat-receiver">
            <div class="aui-chat-receiver-avatar"><img src="../image/widget_dface.png"></div>
            <div class="aui-chat-receiver-cont">
                <div class="aui-chat-left-triangle"></div>
                <div class="aui-chat-status"><i class="aui-iconfont aui-icon-loading aui-chat-progress"></i></div>
                <span>如果想自定义气泡颜色，修改aui-chat-receiver-cont背景和aui-chat-left-triangle的border-color</span>
            </div>
        </div>
    </div>
</body>
<script type="text/javascript" src="../script/api.js" ></script>
<script type="text/javascript" src="../script/sha1.min.js" ></script>
<script type="text/javascript" src="../script/common.js" ></script>
<script type="text/javascript">
var rong_Token = '';
var rong, UIChatBoxObj;
var chatRoomId = '1';	// 预先创建好的聊天室，必须用字符串类型，不能用整数类型，否则iOS上无法加入聊天室

var user_uid = 0;
var user_name = '';
var user_portrait = '';

apiready = function(){
	user_uid = $api.getStorage('user_uid');
	user_name = $api.getStorage('user_name');
	user_portrait = $api.getStorage('user_portrait');

	rong = api.require('rongCloud2');
	UIChatBoxObj = api.require('UIChatBox');
	
	RongCloud_getToken(user_uid, user_name, user_portrait );
	
	openChatBox();
}

// 获取Token
function RongCloud_getToken(userId, name, portraitUri) {
	rong_Token = $api.getStorage('rong_Token');
	if( rong_Token ){
		RongCloud_init();
		return true;
	}
	
	var AppKey = 'lmxuhwagxptgd';
	var AppSecret = 'FfhViX0GkX1';
    var Nonce = Math.floor(Math.random() * 1000000);
    var Timestamp = new Date().getTime();
    var Signature = hex_sha1(AppSecret + Nonce + Timestamp);
    api.ajax({
        url: 'https://api.cn.ronghub.com/user/getToken.json',
        method: 'post',
        headers: {
            "App-Key": AppKey,
            "Nonce": Nonce,
            "Timestamp": Timestamp,
            "Signature": Signature,
            "Content-Type": "application/x-www-form-urlencoded"
        },
        data: {
            values: {
                "userId": userId,
                "name": name,
                "portraitUri": portraitUri,
            }

        }
    },
    function(ret, err) {
        if (ret) {
            if(parseInt(ret.code) == 200){	// 获取成功
            	$api.setStorage('rong_Token', ret.token);
            	rong_Token = ret.token;
            	RongCloud_init();
            }else{
				api.toast({
				    msg: ret.code+'：其他错误',
				    duration:2000,
				    location: 'middle'
				});
            }
        } else {
            showAjaxErrMsg(err.code);
        }
    });
}

// 初始化融云 SDK，调用 connect 连接前务必保证调用此方法
function RongCloud_init(){
	log('rong_Token：'+rong_Token);
	rong.init(function(ret, err){
	    if (ret.status == 'success'){
	    	log('初始化融云 SDK成功');
	    	RongCloud_setConnectionStatusListener();
			RongCloud_setOnReceiveMessageListener();
			RongCloud_connect();
			
	    }else{
	    	log('初始化融云 SDK失败：#'+err.code);
	    }
	});
}

// 设置连接状态变化的监听器，请在调用 init 方法之后，调用 connect 方法之前设置
function RongCloud_setConnectionStatusListener(){
	log( '开始加载连接状态变化监听器...' );
	rong.setConnectionStatusListener(function(ret, err){
		switch(ret.result.connectionStatus)
		{
		case 'CONNECTED':
		  log( '连接成功' );
		  break;
		case 'CONNECTING':
		  log( '连接中...' );
		  break;
		case 'DISCONNECTED':
		  log( '断开连接' );
		  break;
		case 'KICKED':
		  log( '用户账户在其他设备登录，本机下线' );
		  break;
		case 'NETWORK_UNAVAILABLE':
		  log( '网络不可用' );
		  break;
		case 'SERVER_INVALID':
		  log( '服务器异常或无法连接' );
		  break;
		case 'TOKEN_INCORRECT':
		  log( 'Token不正确' );
		  break;
		}
	});
}

// 设置接收消息的监听器，请在调用 init 方法之后，调用 connect 方法之前设置
function RongCloud_setOnReceiveMessageListener(){
	log( '开始加载收消息监听器...' );
	rong.setOnReceiveMessageListener(function (ret, err) {
	    log('收消息监听器：'+JSON.stringify(ret.result.message));
	});
}

// 连接融云 IM 服务器，进行后续各种方法操作前务必要先调用此方法
function RongCloud_connect(){
	log('开始融云IM服务器...');
	rong.connect({
	    token: rong_Token
	    },
	    function(ret, err){
	        if (ret.status == 'success'){
	        	log('融云IM服务器连接成功：uid '+ret.result.userId);
	        	setTimeout("RongCloud_joinChatRoom();", 1000);
	        }else{
	     		log('融云IM服务器连接失败：#'+err.code);
	        }
	});
}

// 当前用户加入某聊天室
function RongCloud_joinChatRoom(){
	rong.joinChatRoom({
	        chatRoomId: chatRoomId,
	        defMessageCount: '3'
	    }, function (ret, err) {
	        if (ret.status == 'success'){
	        	log('加入聊天室成功：'+ret.status);
				api.toast({
				    msg: '加入聊天室成功：'+ret.status,
				    duration:2000,
				    location: 'middle'
				});
	        }else{
	        	log('加入聊天室失败：#'+err.code);
				api.toast({
				    msg: '加入聊天室失败：#'+err.code,
				    duration:2000,
				    location: 'middle'
				});
	        }
	});
}


// 打开评论框
function openChatBox(){
	UIChatBoxObj.open({
	    placeholder: '说点什么',
	    maxRows: 4,
	    emotionPath: 'widget://image/UIChatBox/emotion',
	    styles: {
	        inputBar: {
	            borderColor: '#d9d9d9',
	            bgColor: '#f2f2f2'
	        },
	        inputBox: {
	            borderColor: '#B3B3B3',
	            bgColor: '#fdfdfd'
	        },
	        emotionBtn: {
	            normalImg: 'widget://image/UIChatBox/face1.png'
	        },
	        keyboardBtn: {
	            normalImg: 'widget://image/UIChatBox/key1.png'
	        },
	        indicator: {
	            target: 'both',
	            color: '#c4c4c4',
	            activeColor: '#9e9e9e'
	        }
	    },
	}, function(ret){			
	    //点击发送按钮
	    if(ret.eventType == 'send'){
			if( user_uid<1 ){
				api.toast({
				    msg: '请先登录',
				    duration:2000,
				    location: 'middle'
				});
				UIChatBoxObj.closeKeyboard();	// 收起键盘
				return false;
			}
			
			if( ret.msg.length<1 ){
				api.toast({
				    msg: '请填写内容',
				    duration:2000,
				    location: 'middle'
				});
				return false;
			}
	    
	        sendMessage( ret.msg );
	    }
	});

}

// 发送文字消息
function sendMessage( msg ){
	var extra = user_uid+','+user_name+','+user_portrait;

	rong.sendTextMessage({
	        conversationType: 'CHATROOM',
	        targetId: chatRoomId,
	        text: msg,
	        extra: extra
	    }, function (ret, err) {
	    	UIChatBoxObj.closeKeyboard();	// 收起键盘
	        if (ret.status == 'prepare')
	            alert('发送prepare：' + JSON.stringify(ret.result.message) );
	        else if (ret.status == 'success')
	            alert('发送success：' + ret.result.message.messageId );
	        else if (ret.status == 'error')
	        	alert('发送error：' + err.code );
	    }
	);
}


</script>
</html>